﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;


public class ConfigController
{

    private static ConfigController m_Instance;
    private ConfigController() { }
    public static ConfigController Instance{
        get {
            if (m_Instance == null) {
                m_Instance = new ConfigController();
            }
            return m_Instance;
        }
    }
    
    private bool isInited = false;
    //private Dictionary<string, Dictionary<int, Dictionary<string, string>>> Data = new Dictionary<string, Dictionary<int, Dictionary<string, string>>>();

    public Dictionary<Type, Dictionary<int, System.Object>> ConfigData = new Dictionary<Type, Dictionary<int, object>>();


    public void Init()
    {
        if (!isInited)
        {
            isInited = true;

            //string path = ResUpdate.LOCAL_RES_PATH;
            //if (!File.Exists(path + "version.txt"))
            //{
            //    path = Application.streamingAssetsPath + "/Data/";
            //}

            string path = Application.streamingAssetsPath + "/Data/";

            DirectoryInfo di = new DirectoryInfo(path);
            FileInfo[] files = di.GetFiles("*.txt");
            foreach (var file in files)
            {
                string fileName = file.Name;
                if (file.Name == "version.txt")
                {
                    continue;
                }

                //从配置文件路径加载出配置文件文本类容
                ArrayList textData = FileHelper.LoadFile(path, fileName);

                //获取配置文件无扩展名且首字母大写的名字
                fileName = Utils.FirstToUpper(fileName).Split('.')[0];


                //配置文件对象字典
                Dictionary<int, object> fileObjectDic = new Dictionary<int, object>();
                //反射出配置文件类型
                Type type = Assembly.Load("Assembly-CSharp").GetType(fileName);
                ConfigData.Add(type, fileObjectDic);
                //对象属性集合
                string[] keys = new string[textData.Count];

                for (int i = 0; i < textData.Count; i++)
                {
                    System.Object obj = Assembly.Load("Assembly-CSharp").CreateInstance(fileName);
                    string rowData = textData[i].ToString();
                    //0 is Chinese tag!
                    if (!rowData.Equals(""))
                    {
                        //第0行是中文注释，忽略
                        if (i == 0)
                        {
                            continue;
                        }
                        string[] colData = rowData.Split('\t');

                        //第一行用于Key
                        if (i == 1)
                        {
                            keys = colData;
                            continue;
                        }
                        //第二行用户数据类型，忽略
                        if (i == 2)
                        {
                            continue;
                        }
                        
                        int Id = int.Parse(colData[0].Trim());
                        for (int j = 0; j < colData.Length; j++)
                        {
                            Utils.SetModelValue(Utils.FirstToUpper(keys[j].Trim()), colData[j].Trim(), obj);
                        }
                        try
                        {
                            fileObjectDic.Add(Id, obj);
                        }
                        catch (Exception e)
                        {
                            Debug.LogError(e);
                            Debug.LogError(type + "   " + colData[0]);
                        }


                    }

                    #region backup

                    //ArrayList fileData = FileHelper.LoadFile(path, "version.txt");
                    //for (int f = 0; f < fileData.Count; f++)
                    //{
                    //    //从配置文件列表读取出配置文件全名XX.txt
                    //    string fileName = fileData[f].ToString().Split(',')[0].Trim();
                    //    if (!fileName.Equals(""))
                    //    {
                    //        //从配置文件路径加载出配置文件文本类容
                    //        ArrayList textData = FileHelper.LoadFile(path, fileName);

                    //        //获取配置文件无扩展名且首字母大写的名字
                    //        fileName = Tools.FirstToUpper(fileName).Split('.')[0];


                    //        //配置文件对象字典
                    //        Dictionary<int, object> fileObjectDic = new Dictionary<int, object>();
                    //        //反射出配置文件类型
                    //        m_Type type = Assembly.Load("Assembly-CSharp").GetType(fileName);
                    //        ConfigData.Add(type, fileObjectDic);
                    //        //对象属性集合
                    //        string[] keys = new string[textData.Count];

                    //        for (int i = 0; i < textData.Count; i++)
                    //        {
                    //            System.Object obj = Assembly.Load("Assembly-CSharp").CreateInstance(fileName);
                    //            string rowData = textData[i].ToString();
                    //            //0 is Chinese tag!
                    //            if (!rowData.Equals(""))
                    //            {
                    //                //第0行是中文注释，忽略
                    //                if (i == 0)
                    //                {
                    //                    continue;
                    //                }
                    //                string[] colData = rowData.Split('\t');

                    //                //第一行用于Key
                    //                if (i == 1)
                    //                {
                    //                    keys = colData;
                    //                    continue;
                    //                }
                    //                //第二行用户数据类型，忽略
                    //                if (i==2)
                    //                {
                    //                    continue;
                    //                }


                    //                int Id = int.Parse(colData[0].Trim());
                    //                for (int j = 0; j < colData.Length; j++)
                    //                {
                    //                    Tools.SetModelValue(Tools.FirstToUpper(keys[j].Trim()), colData[j].Trim(), obj);
                    //                }
                    //                try
                    //                {
                    //                    fileObjectDic.Add(Id, obj);
                    //                }
                    //                catch (Exception e)
                    //                {
                    //                    Debug.Log(e);
                    //                    Debug.Log(type + "   " + colData[0]);
                    //                }

                    //            }
                    //        }
                    //    }
                    //} 

                    #endregion


                }
            }
            Debug.Log("配置文件加载完成...");
        }
    }

	public Dictionary<int, T> GetConfigs<T>(Dictionary<string, string> scouts) where T : class
	{
		Type type = typeof(T);
		Dictionary<int, T> tmpDic = new Dictionary<int, T>();
		var list = GetConfigs<T> ();
		foreach(KeyValuePair<int,T> kv in list)
		{
			var putIn = true;
			foreach(KeyValuePair<string,string> skv in scouts)
			{
				var p = type.GetProperty (skv.Key).GetValue (kv.Value, null);
				if (!p.ToString().Equals(skv.Value))
				{
					putIn = false;
					break;
				}
			}
			if (putIn)
				tmpDic.Add(kv.Key, kv.Value);
		}
		return tmpDic;
	}

    public Dictionary<int, T> GetConfigs<T>() where T : class
	{
		Dictionary<int, T> tmpDic = new Dictionary<int, T> ();
		Type type = typeof(T);
		if (!ConfigData.ContainsKey (type))
			return tmpDic;
		foreach (var item in ConfigData[type]) {
			tmpDic.Add (item.Key, item.Value as T);
		}
		return tmpDic;
	}

    public T GetConfig<T>(int id) where T : class
    {
        Type type = typeof(T);
        T t = null;
        if (ConfigData.ContainsKey(type))
        {
            foreach (var item in ConfigData[type].Where(item => item.Key == id))
            {
                t = item.Value as T;
                break;
            }
        }
        if (t == null)
        {
            throw new Exception("你所查找的ID不存在 " + type + " ,ID--" + id);
        }
        return t;
    }


    public static bool IdIsEquipment(int id)
    {
        if (id > 10000 && id < 20000)
        {
            return true;
        }
        return false;
    }
    public static bool IdIsGoods(int id)
    {
        if (id > 20000 && id < 30000)
        {
            return true;
        }
        return false;
    }
}

